#coding:utf-8

import tensorflow as tf
import numpy as np
from PIL import Image
import mnist as m
import os

mnist = m.read_data_sets("MNIST_data", one_hot=True)

def pre_pic(picName):
	img=Image.open(picName)
	reIm=img.resize((28,28),Image.ANTIALIAS)
	#Image.ANTIALIAS消除锯齿
	im_arr=np.array(reIm.convert('L'))
	#reIm.convert('L')灰度转换
	threshold=90
	for i in range(28):
		for j in range(28):
			im_arr[i][j]=255-im_arr[i][j]
			#反色to黑底白字
			if(im_arr[i][j]<threshold):
				im_arr[i][j]=0
			else:
				im_arr[i][j]=255
				#0=黑色
	nm_arr=im_arr.reshape([1,784])
	nm_arr=nm_arr.astype(np.float32)
	img_ready=np.multiply(nm_arr,1.0/255.0)

	return img_ready

def application():
	sess = tf.InteractiveSession()

	x = tf.placeholder("float", shape=[None, 784])
	y_ = tf.placeholder("float", shape=[None, 10])

	W = tf.Variable(tf.zeros([784, 10]))
	b = tf.Variable(tf.zeros([10]))

	sess.run(tf.global_variables_initializer())

	y = tf.nn.softmax(tf.matmul(x, W) + b)

	cross_entropy = -tf.reduce_sum(y_ * tf.log(y))

	train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

	for i in range(1000):
		batch = mnist.train.next_batch(50)
		train_step.run(feed_dict={x: batch[0], y_: batch[1]})

	for i in range(10):
		filename=str(i)+'.png'
		testPic=os.path.join('mnist_pic',filename)
		#复制路径
		testPicArr=pre_pic(testPic)
		preValue=tf.argmax(y, 1)
		preValue=sess.run(preValue,feed_dict={x:testPicArr})
		print ("The prediction number is:",preValue)
	
def main():
	application()
main()
